<template>
    <div class="common-layout">
        <el-container>
            <el-main style="padding-bottom: 80px;">
                <el-form ref="customerFormRef" :model="customerForm" :rules="rules" label-width="120px">
                    <!-- 基础信息 -->
                    <el-card style="margin-bottom: 20px;">
                        <template #header>
                            <span style="font-weight: bold;">新增客户</span>
                        </template>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="客户编码" prop="customerCode">
                                    <el-input v-model="customerForm.customerCode" placeholder="自动获取系统编号"
                                        class="readonly-input" readonly>
                                        <template #append>
                                            <el-button @click="generateCustomerCode" :loading="generatingCustomerCode">
                                                自动生成
                                            </el-button>
                                        </template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="客户名称" prop="customerName">
                                    <el-input v-model="customerForm.customerName" placeholder="请输入客户名称" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="所属行业" prop="industryId">
                                    <el-select v-model="customerForm.industryId" placeholder="请选择所属行业"
                                        style="width: 100%">
                                        <el-option v-for="item in industryList" :key="item.industryId"
                                            :label="item.industryName" :value="item.industryId" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="客户来源" prop="customerSourceId">
                                    <el-select v-model="customerForm.customerSourceId" placeholder="请选择客户来源"
                                        style="width: 100%">
                                        <el-option v-for="item in customerSourceList" :key="item.customerSourceId"
                                            :label="item.customerSourceName" :value="item.customerSourceId" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="联系人" prop="customerContact">
                                    <el-input v-model="customerForm.customerContact" placeholder="请输入联系人" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="联系电话" prop="contactPhone">
                                    <el-input v-model="customerForm.contactPhone" placeholder="请输入联系电话" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="电子邮箱" prop="customerEmail">
                                    <el-input v-model="customerForm.customerEmail" placeholder="请输入电子邮箱" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="销售部门" prop="organizationId">
                                    <el-input v-model="customerForm.organizationName" placeholder="请选择销售部门" readonly
                                        @click="openOrgDialog">
                                        <template #suffix>
                                            <el-icon>
                                                <Search />
                                            </el-icon>
                                        </template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="销售负责人" prop="userId">
                                    <el-input v-model="customerForm.userName" placeholder="请选择销售负责人" readonly
                                        @click="openUserDialog">
                                        <template #suffix>
                                            <el-icon>
                                                <Search />
                                            </el-icon>
                                        </template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="客户状态" prop="customerState">
                                    <el-radio-group v-model="customerForm.customerState">
                                        <el-radio :label="0">启用</el-radio>
                                        <el-radio :label="1">禁用</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="24">
                                <el-form-item label="客户地址" prop="contactAddress">
                                    <el-input v-model="customerForm.contactAddress" type="textarea" :rows="3"
                                        placeholder="请输入客户地址" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="24">
                                <el-form-item label="备注" prop="customerNote">
                                    <el-input v-model="customerForm.customerNote" type="textarea" :rows="3"
                                        placeholder="请输入备注信息" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-card>

                    <!-- 财务信息 -->
                    <el-card style="margin-bottom: 20px;">
                        <template #header>
                            <span>财务信息</span>
                        </template>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="账户名称" prop="financeName">
                                    <el-input v-model="customerForm.financeName" placeholder="请输入账户名称" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="纳税人识别号" prop="taxpayerNumber">
                                    <el-input v-model="customerForm.taxpayerNumber" placeholder="请输入纳税人识别号" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="银行账户" prop="bankAccount">
                                    <el-input v-model="customerForm.bankAccount" placeholder="请输入银行账户" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="开户银行" prop="accountBank">
                                    <el-input v-model="customerForm.accountBank" placeholder="请输入开户银行" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20">
                            <el-col :span="24">
                                <el-form-item label="开户行地址" prop="bankAddress">
                                    <el-input v-model="customerForm.bankAddress" placeholder="请输入开户行地址" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-card>

                    <!-- 文件上传 -->
                    <el-card>
                        <template #header>
                            <span>上传附件</span>
                        </template>
                        <el-upload :action="uploadAction" :headers="uploadHeaders" :file-list="fileList"
                            :before-upload="beforeUpload" :on-success="handleUploadSuccess" :on-remove="handleRemove"
                            multiple drag>
                            <el-icon class="el-icon--upload">
                                <UploadFilled />
                            </el-icon>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            <template #tip>
                                <div class="el-upload__tip">支持doc, pdf, rar格式文件，大小不超过200MB</div>
                            </template>
                        </el-upload>
                        <div v-if="fileList.length > 0" style="margin-top: 20px;">
                            <h4>已上传文件：</h4>
                            <div v-for="(file, index) in fileList" :key="index"
                                style="display: flex; align-items: center; margin: 8px 0;">
                                <span>{{ file.name }}</span>
                                <el-button type="danger" size="small" :icon="Delete" @click="handleRemoveFile(index)"
                                    style="margin-left: 10px;">
                                    删除
                                </el-button>
                            </div>
                        </div>
                    </el-card>
                </el-form>
            </el-main>
        </el-container>

        <!-- 部门选择对话框 -->
        <el-dialog v-model="showOrgDialog" title="选择部门" width="600px">
            <div style="margin-bottom: 16px;">
                <el-input v-model="orgSearchText" placeholder="搜索部门名称" clearable>
                    <template #prefix>
                        <el-icon>
                            <Search />
                        </el-icon>
                    </template>
                </el-input>
            </div>
            <el-tree ref="orgTreeRef" :data="organizationTree" node-key="organizationId" :props="orgTreeProps"
                highlight-current default-expand-all :expand-on-click-node="false" :filter-node-method="filterOrgNode"
                @node-click="handleSelectOrg" style="max-height: 400px; overflow: auto;" />
        </el-dialog>

        <!-- 用户选择对话框 -->
        <el-dialog v-model="showUserDialog" title="选择用户" width="400px">
            <div style="margin-bottom: 16px;">
                <el-input v-model="userSearchText" placeholder="搜索用户名称" clearable>
                    <template #prefix>
                        <el-icon>
                            <Search />
                        </el-icon>
                    </template>
                </el-input>
            </div>
            <el-table :data="filteredUserList" @row-click="handleSelectUser" style="cursor: pointer;">
                <el-table-column prop="userName" label="用户名称" />
            </el-table>
        </el-dialog>

        <!-- 固定底部保存按钮 -->
        <div class="fixed-footer">
            <div class="footer-content" style="float: right;">
                <el-button @click="router.push('/Getcustomer')">关闭</el-button>
                <el-button @click="">取消</el-button>
                <el-button type="primary" @click="saveCustomer" :loading="saving">保存</el-button>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Delete, Search, UploadFilled } from '@element-plus/icons-vue'
import myaxios from '@/http/MyAxios'
import moment from 'moment'

const route = useRoute()
const router = useRouter()

// 表单引用
const customerFormRef = ref<FormInstance>()
const generatingCustomerCode = ref(false)

// 表单数据
const customerForm = reactive({
    customerId: '',
    customerCode: '',
    customerName: '',
    industryId: '',
    customerSourceId: '',
    customerContact: '',
    contactPhone: '',
    customerEmail: '',
    organizationId: '',
    organizationName: '',
    userId: '',
    userName: '',
    customerState: 0,
    contactAddress: '',
    customerNote: '',
    // 财务信息
    financeId: '',
    financeName: '',
    taxpayerNumber: '',
    bankAccount: '',
    accountBank: '',
    bankAddress: '',
    // 操作信息
    createor: '',
    createrTime: '',
})

const TIME_SEGMENT_ORDER = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
const pad = (n: number, len = 2) => `${n}`.padStart(len, '0')

const buildCodeFromRule = (rule: any) => {
    const now = new Date()
    const segments = (rule?.timeRule || '')
        .split(',')
        .map((s: string) => s.trim().toUpperCase())
        .filter(Boolean)
        .sort((a: string, b: string) => {
            const indexA = TIME_SEGMENT_ORDER.indexOf(a)
            const indexB = TIME_SEGMENT_ORDER.indexOf(b)
            if (indexA === -1 && indexB === -1) return 0
            if (indexA === -1) return 1
            if (indexB === -1) return -1
            return indexA - indexB
        })

    const datePart = segments
        .map((seg: string) => {
            switch (seg) {
                case 'YYYY': return String(now.getFullYear())
                case 'YY': return String(now.getFullYear()).slice(-2)
                case 'MM': return pad(now.getMonth() + 1)
                case 'DD': return pad(now.getDate())
                case 'HH': return pad(now.getHours())
                case 'MI': return pad(now.getMinutes())
                case 'SS': return pad(now.getSeconds())
                default: return ''
            }
        })
        .join('')

    const seq = '1'.padStart(rule?.serialLength || 3, '0')
    return `${rule?.codePrefix || ''}${datePart}${seq}`
}

const requestNumber = async (targetCode: string, targetName: string) => {
    try {
        const res = await myaxios.get('/api/Number/GenerateNumber', {
            params: { targetCode, targetName }
        })
        if (res?.data?.code === 200 && res?.data?.data) {
            return String(res.data.data)
        }
        throw new Error(res?.data?.message || '生成编号失败')
    } catch (err) {
        console.warn(`[numbering] GenerateNumber 接口不可用 (${targetCode})，尝试规则生成`, err)
        const ruleRes = await myaxios.get('/api/Number/QueryNumberingRules', {
            params: { targetCode, targetName }
        })
        const list = Array.isArray(ruleRes?.data?.data) ? ruleRes.data.data : []
        if (list.length > 0) {
            return buildCodeFromRule(list[0])
        }
        throw new Error('未找到对应的编号规则，请先配置编号规则')
    }
}

const generateCustomerCode = async () => {
    if (generatingCustomerCode.value) return
    generatingCustomerCode.value = true
    try {
        customerForm.customerCode = await requestNumber('Customer', '客户')
        ElMessage.success('编号生成成功')
    } catch (err: any) {
        ElMessage.error(err?.message || '生成编号失败')
    } finally {
        generatingCustomerCode.value = false
    }
}

// 表单验证规则
const rules = {
    customerName: [
        { required: true, message: '请输入客户名称', trigger: 'blur' }
    ],
    industryId: [
        { required: true, message: '请选择所属行业', trigger: 'change' }
    ],
    customerSourceId: [
        { required: true, message: '请选择客户来源', trigger: 'change' }
    ],
}

// 接口类型定义
interface IndustryItem {
    industryId: string | number
    industryName: string
}

interface CustomerSourceItem {
    customerSourceId: string | number
    customerSourceName: string
}

interface OrganizationItem {
    organizationId: string | number
    organizationName: string
    organizationCode?: string
    children?: OrganizationItem[]
}

interface UserItem {
    userId: string | number
    userName: string
    userCode?: string
    organizationId?: string | number
    organizationid?: string | number
    orgId?: string | number
    orgid?: string | number
    organizationName?: string
}

// 下拉列表数据
const industryList = ref<IndustryItem[]>([])
const customerSourceList = ref<CustomerSourceItem[]>([])
const organizationTree = ref<OrganizationItem[]>([])
const orgTreeProps = { label: 'organizationName', children: 'children' }
const userList = ref<UserItem[]>([])

// 对话框显示状态
const showOrgDialog = ref(false)
const showUserDialog = ref(false)
const saving = ref(false)
const userSearchText = ref('')
const orgSearchText = ref('')
const orgTreeRef = ref()

const filterOrgNode = (value: string, data: OrganizationItem) => {
    if (!value) return true
    return data.organizationName?.toLowerCase().includes(value.toLowerCase())
}

watch(orgSearchText, (val) => {
    if (orgTreeRef.value?.filter) {
        orgTreeRef.value.filter(val)
    }
})

// 文件上传
const uploadAction = ref('api/Customer/UploadFile')
const uploadHeaders = ref({})
const fileList = ref<Array<{ name: string; url: string; uid?: number; raw?: File }>>([])

// 过滤用户列表
const getUserOrgId = (user: UserItem) => {
    return user.organizationId ?? user.organizationid ?? user.orgId ?? user.orgid ?? ''
}

const filteredUserList = computed(() => {
    const orgId = customerForm.organizationId
    if (!orgId) {
        return []
    }
    const keyword = userSearchText.value?.toLowerCase() || ''
    return userList.value.filter(user => {
        const matchOrg = String(getUserOrgId(user)) === String(orgId)
        const matchKeyword = !keyword || user.userName?.toLowerCase().includes(keyword)
        return matchOrg && matchKeyword
    })
})

const isRootDictionary = (item: any) =>
    !item.parentId || item.parentId === 0 || item.parentId === '0' || item.parentId === null

const matchDictionary = (item: any, names: string[], codes: string[]) => {
    const name = (item.dictionaryName || '').toLowerCase()
    const code = (item.dictionaryCode || '').toLowerCase()
    return names.some(n => name === n.toLowerCase() || name.includes(n.toLowerCase())) ||
        codes.some(c => code === c.toLowerCase())
}

const findDictionaryParentId = async (nameCandidates: string[], codeCandidates: string[]) => {
    const commonParams = { Pageindex: 1, PageSize: 1000 }
    try {
        const listRes = await myaxios.get('/api/Dictionary/GetDictionaryList', { params: commonParams })
        const list = listRes.data?.data?.data || []
        const found = list.find((item: any) => isRootDictionary(item) && matchDictionary(item, nameCandidates, codeCandidates))
        if (found?.dictionaryId) return found.dictionaryId
    } catch (error) {
        console.warn('获取字典列表失败', error)
    }

    for (const name of nameCandidates) {
        try {
            const res = await myaxios.get('/api/Dictionary/GetDictionaryList', {
                params: { DictionaryName: name, Pageindex: 1, PageSize: 200 }
            })
            const list = res.data?.data?.data || []
            const found = list.find((item: any) => isRootDictionary(item))
            if (found?.dictionaryId) return found.dictionaryId
        } catch (error) {
            console.warn(`按名称 ${name} 获取字典失败`, error)
        }
    }
    return null
}

const fetchDictionaryChildren = async (parentId: string | number | null) => {
    if (!parentId) return []
    try {
        const res = await myaxios.get('/api/Dictionary/GetDictionaryChildren', {
            params: { ParentId: parentId, Pageindex: 1, PageSize: 1000 }
        })
        return res.data?.data?.data || []
    } catch (error) {
        console.warn('获取字典子项失败', error)
        return []
    }
}

const loadIndustryList = async () => {
    const parentId = await findDictionaryParentId(['所属行业', '行业'], ['industry'])
    const children = await fetchDictionaryChildren(parentId)
    industryList.value = children.map((item: any) => ({
        industryId: item.dictionaryId,
        industryName: item.dictionaryName
    }))
}

const loadCustomerSourceList = async () => {
    const parentId = await findDictionaryParentId(['客户来源'], ['customersource', 'customer_source'])
    const children = await fetchDictionaryChildren(parentId)
    customerSourceList.value = children.map((item: any) => ({
        customerSourceId: item.dictionaryId,
        customerSourceName: item.dictionaryName
    }))
}

// 转换部门树数据
const transformOrgTree = (nodes: any): OrganizationItem[] => {
    if (!nodes) return []
    const list = Array.isArray(nodes) ? nodes : [nodes]
    return list.map((item: any) => ({
        organizationId: item.organizationId ?? item.organizationid ?? item.id ?? item.orgId ?? item.orgid ?? '',
        organizationName: item.organizationName ?? item.organizationname ?? item.label ?? item.name ?? '',
        organizationCode: item.organizationCode ?? item.organizationcode ?? item.code,
        children: transformOrgTree(
            item.children ??
            item.childrens ??
            item.childList ??
            item.childNodes ??
            item.childs ??
            item.nodes ??
            []
        )
    }))
}

// 获取部门树
const getOrganizationTree = () => {
    myaxios.get('api/Organization/GetOrganizationTree', { params: { parentid: 0 } }).then((res: any) => {
        const payload = Array.isArray(res.data) ? res.data
            : res.data?.data ?? res.data?.datas ?? []
        organizationTree.value = transformOrgTree(payload)
    }).catch((err: any) => {
        console.error('获取部门树失败:', err)
        organizationTree.value = []
    })
}

// 获取用户列表
const getUserList = () => {
    myaxios.get('api/Supplier/GetUser').then((res: any) => {
        if (res.data.code === 200) {
            userList.value = res.data.data || []
        }
    }).catch((err: any) => {
        console.error('获取用户列表失败:', err)
    })
}

// 打开部门选择对话框
const openOrgDialog = () => {
    orgSearchText.value = ''
    showOrgDialog.value = true
}

// 打开用户选择对话框
const openUserDialog = () => {
    if (!customerForm.organizationId) {
        ElMessage.warning('请先选择销售部门')
        return
    }
    userSearchText.value = ''
    showUserDialog.value = true
}

// 选择部门
const handleSelectOrg = (row: OrganizationItem) => {
    customerForm.organizationId = String(row.organizationId)
    customerForm.organizationName = row.organizationName
    customerForm.userId = ''
    customerForm.userName = ''
    showOrgDialog.value = false
}

// 选择用户
const handleSelectUser = (row: UserItem) => {
    customerForm.userId = String(row.userId)
    customerForm.userName = row.userName
    showUserDialog.value = false
}

// 文件上传前验证
const beforeUpload = (file: File) => {
    const isValidType = ['application/msword', 'application/pdf', 'application/x-rar-compressed',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
        .includes(file.type) || file.name.endsWith('.doc') || file.name.endsWith('.pdf') ||
        file.name.endsWith('.rar') || file.name.endsWith('.docx')
    const isLt200M = file.size / 1024 / 1024 < 200

    if (!isValidType) {
        ElMessage.error('只能上传doc, pdf, rar格式的文件!')
        return false
    }
    if (!isLt200M) {
        ElMessage.error('文件大小不能超过200MB!')
        return false
    }
    return true
}

// 文件上传成功
const handleUploadSuccess = (response: any, file: any, fileListParam: any) => {
    if (response) {
        if (response.code === 200 || response.status === 'success') {
            ElMessage.success('文件上传成功')
            if (response.data?.url) {
                const index = fileList.value.findIndex((item: any) => item.uid === file.uid)
                if (index > -1 && fileList.value[index]) {
                    fileList.value[index].url = response.data.url
                }
            }
        } else {
            ElMessage.error(response.message || '文件上传失败')
            const index = fileList.value.findIndex((item: any) => item.uid === file.uid)
            if (index > -1) {
                fileList.value.splice(index, 1)
            }
        }
    } else {
        ElMessage.success('文件上传成功')
    }
}

// 移除文件（手动删除）
const handleRemoveFile = (index: number) => {
    fileList.value.splice(index, 1)
    ElMessage.success('文件已移除')
}

// 文件移除回调（el-upload自动调用）
const handleRemove = (file: any) => {
    const index = fileList.value.findIndex((item: any) => item.uid === file.uid)
    if (index > -1) {
        fileList.value.splice(index, 1)
    }
}



// 保存客户信息
const saveCustomer = async () => {
    if (!customerFormRef.value) return

    if (!customerForm.customerCode) {
        await generateCustomerCode()
        if (!customerForm.customerCode) {
            ElMessage.warning('请先生成客户编码')
            return
        }
    }
    try {
        const valid = await customerFormRef.value.validate()
        if (!valid) return

        saving.value = true
        // 自动设置操作人和操作时间 - 从后端获取真实姓名
        let currentUser = localStorage.getItem('username') || ''
        try {
            const res = await myaxios.get('/api/User/GetMyProfile')
            const droot: any = res?.data ?? {}
            const d: any = (droot?.data && Object.keys(droot).length <= 3) ? (droot.data || {}) : droot
            if (d) {
                // 优先使用真实姓名，其次用户名
                currentUser = d.userName || d.realName || d.nickname || currentUser
                // 更新localStorage以便后续使用
                if (currentUser) {
                    localStorage.setItem('username', currentUser)
                }
            }
        } catch (error) {
            console.warn('获取当前用户信息失败，使用本地存储的值:', error)
        }
        const currentTime = moment().format('YYYY-MM-DD HH:mm:ss')
        
        // 更新表单数据中的操作人和操作时间
        customerForm.createor = currentUser
        customerForm.createrTime = currentTime
        
        // 组装提交数据，包含附件信息
        const createData = {
            ...customerForm,
            createor: currentUser,
            createrTime: currentTime,
            files: fileList.value.map(file => ({
                fileName: file.name,
                fileUrl: file.url
            }))
        }

        const res = await myaxios.post('/api/Customer/CreateCustomerWithFinance', createData)

        if (res.data.code === 200) {
            ElMessage.success(res.data.message || '客户创建成功')
            router.push('/GetCustomer')
        } else {
            ElMessage.error(res.data.message || '客户创建失败')
        }
    } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败，请重试')
    } finally {
        saving.value = false
    }
}

// 页面初始化
onMounted(() => {
    loadIndustryList()
    loadCustomerSourceList()
    getOrganizationTree()
    getUserList()
})
</script>

<style scoped>
.common-layout {
    padding: 20px;
    position: relative;
}

.el-card {
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}

.el-form-item {
    margin-bottom: 22px;
}

.el-upload__tip {
    color: #606266;
    font-size: 12px;
    margin-top: 7px;
}

.fixed-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    border-top: 1px solid #e4e7ed;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
    z-index: 1000;
}

.footer-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 16px 20px;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}
</style>